﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using XcoAppSpaces.Core;
using System.Threading;
using Microsoft.Ccr.Core;
using XcoAppSpaces.Transport.Sockets;
using XcoAppSpaces.Contracts.Transport;
using XcoAppSpaces.Contracts.Messaging;
using System.Collections.Generic;
using System.Diagnostics;

namespace test.XcoAppSpaces.SL
{
	[TestClass]
	public class XcoTCPTransportServiceTests
	{
		[TestMethod]
		[Tag("sockets")]
		public void ReceiveManyResponses()
		{
			var transportService = new XcoTCPTransportService();
			transportService.Start();

			var messagesReceived = new List<int>();
			var evt = new ManualResetEvent(false);
			var sw = Stopwatch.StartNew();
			
			transportService.OnMessageReceived += (msg, addr, svc) =>
			{
				int i = BitConverter.ToInt32(msg.Content, 0);
				lock (messagesReceived)
				{
					messagesReceived.Add(i);
					if (messagesReceived.Count == 1000)
					{
						sw.Stop();
						evt.Set();
					}
				}
			};

			transportService.Send(new XcoMessage { Content = new byte[] { 1, 2, 3 }, CausalityContext = new byte[]{4,5,6}, ContentInfo = "test" }, "localhost:4515");
			evt.WaitOne(10000);
			Debug.WriteLine("Time for 1000 Messages: " + sw.Elapsed.TotalSeconds);

			var missingMessages = new List<int>();
			for (int i = 0; i < 1000; i++)
			{
				if (!messagesReceived.Contains(i))
					missingMessages.Add(i);
			}

			Assert.AreEqual(1000, messagesReceived.Count);
		}
	}
}